package impl

import (
	bcomm "hundsun.com/hsl/hschain/blockchain/common"
	"hundsun.com/hsl/hschain/common/types"
	pbledger "hundsun.com/hsl/hschain/protos/ledger"
)

// AddCacheBlock 添加缓存区块
func (chain *BlockChain) AddCacheBlock(blk *pbledger.Block) {
	chain.blockCache.Set(bcomm.GenTempBlockKeyByHeight(blk.Header.Number), blk)
}

// AddCacheExecutedBlock 添加缓存执行后区块
func (chain *BlockChain) AddCacheExecutedBlock(executedBlock *pbledger.ExecutedBlock) {
	chain.blockCache.Set(bcomm.GenTempExecutedBlockKeyByHeight(executedBlock.Block.Header.Number), executedBlock)
}

// GetCacheBlock 根据高度获取缓存区块
func (chain *BlockChain) GetCacheBlock(height uint64) (*pbledger.Block, error) {
	var blk = &pbledger.Block{}
	blockEntry, ok := chain.blockCache.Get(bcomm.GenTempBlockKeyByHeight(height))
	if !ok {
		return nil, types.ErrNotFound
	}

	blk = blockEntry.(*pbledger.Block)
	return blk, nil
}

// GetCacheExecutedBlock 根据高度获取缓存执行后区块
func (chain *BlockChain) GetCacheExecutedBlock(height uint64) (*pbledger.ExecutedBlock, error) {
	var executedBlk = &pbledger.ExecutedBlock{}
	//从缓存的最新区块中尝试获取，最新区块的add是在执行block流程中处理
	blockEntry, ok := chain.blockCache.Get(bcomm.GenTempExecutedBlockKeyByHeight(height))
	if !ok {
		return nil, types.ErrNotFound
	}

	executedBlk = blockEntry.(*pbledger.ExecutedBlock)
	return executedBlk, nil
}

// DelCacheBlock 根据高度删除缓存区块
func (chain *BlockChain) DelCacheBlock(height uint64) {
	chain.blockCache.Delete(bcomm.GenTempBlockKeyByHeight(height))
}

// DelCacheExecutedBlock 根据高度删除缓存执行后区块
func (chain *BlockChain) DelCacheExecutedBlock(height uint64) {
	chain.blockCache.Delete(bcomm.GenTempExecutedBlockKeyByHeight(height))
}
